package com.bs.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bs.bean.Resource;
import com.bs.service.ResourceService;
import com.bs.utils.DBUtils;
import com.bs.utils.Result;

import sun.misc.BASE64Encoder;
/*控制层：ResourceController*/
@RestController
@RequestMapping(value="/json/resource",produces="application/json; charset=utf-8")
public class ResourceJsonController {
//	注入ResourceService对象
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpSession session;
	@Autowired
	private ServletContext context;
//	查询数据返回到/page/resource/resourceItem.jsp页面
	@RequestMapping("/findAll")
	public Result findAll(Resource resource, @RequestParam(required = false, defaultValue = "true") Boolean mode) {
		try {
			List<Resource> list = resourceService.findAll(resource,mode);
			return Result.success().put("list",list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
		
	}
	@RequestMapping("/findById")
	public Result findById(Integer id) {
		try {
			Resource resource = resourceService.findById(id);
			return Result.success().put("resource",resource);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	@RequestMapping("/download")
	public void download(Integer id,HttpServletResponse response) throws Exception {
		
		Resource resource = resourceService.findById(id);
		System.out.println("download---------"+resource);
		String name=resource.getFile();
		String filename = DBUtils.basePathname+"/" + name;
		String contentType = context.getMimeType(filename);
		response.setHeader("Content-Type", contentType);
		String contentDisposition = "attachment;filename=" + filenameEncoding(name, request);
		response.setHeader("Content-Disposition", contentDisposition);

		InputStream inputStream = new FileInputStream(filename);
		OutputStream fileOutputStream = response.getOutputStream();
		byte[] bs = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(bs)) != -1) {
			fileOutputStream.write(bs, 0, len);
		}
		inputStream.close();
	}

	public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
		String agent = request.getHeader("User-Agent"); //获取浏览器
		if (agent.contains("Firefox")) {
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filename = "=?utf-8?B?"
					+ base64Encoder.encode(filename.getBytes("utf-8"))
					+ "?=";
		} else if(agent.contains("MSIE")) {
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}
		
//	删除数据
	public void deleteById(String idString) {
		if (idString!=null) {
			Integer id = Integer.valueOf(idString);
			//	删除数据库中resource中的对应id的数据
			resourceService.deleteById(id);
		}
	}
//	根据resourceItem.jsp页面传递的id，调用resourceServlet#deleteById(id)方法删除resource表中的数据，重定向到findAll请求
	@RequestMapping("/deleteById")
	public Result deleteById() {
//		单条删除
		deleteById(request.getParameter("id"));
//		批量删除
		String ids = request.getParameter("ids");
		if (ids!=null) {
			for (String id : ids.split(",")) {
				deleteById(id);
			}
		}
			return Result.success();
	}
	@RequestMapping("/delete")
	public Result delete(Resource resource) {
		try {
			resourceService.delete(resource);
			return Result.success("删除成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	@RequestMapping("/deleteByIds")
	public Result deleteByIds(List<Integer> list) {
		try {
			resourceService.deleteByIds(list);
			return Result.success("删除成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	@RequestMapping("/updateByIdSelective")
	public Result updateByIdSelective(Resource resource,@RequestParam(required=false) MultipartFile fileFile) {
		try {
			resource.setFile(DBUtils.setFile(fileFile));
			resourceService.updateByIdSelective(resource);
			return Result.success("更新成功");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	
//	根据resourceUpdate.jsp页面传递的数据，更新数据库，重定向到findAll请求
	@RequestMapping("/updateById")
	public Result updateById(Resource resource,@RequestParam(required=false) MultipartFile fileFile) {
		try {
			resource.setFile(DBUtils.setFile(fileFile));
			resourceService.updateByIdSelective(resource);
		} catch (Exception e) {
			e.printStackTrace();
		}
			return Result.success();
	}

//	根据resourceInsert.jsp页面传递的数据，封装在resource对象中插入数据库，重定向到重定向到findAll请求
	@RequestMapping("/insert")
	public Result insert(Resource resource,@RequestParam(required=false) MultipartFile fileFile) {
		try {
			resource.setFile(DBUtils.setFile(fileFile));
			resourceService.insert(resource);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
			return Result.success();
	}
}